import React from 'react'
import { actions } from 'mirrorx'
import { createForm } from 'rc-form'
import { Checkbox } from 'antd-mobile'

import HolderBox from './insure-component/holder-box'
import InsuranceBox from './insure-component/insurance-box'
import TrialItems from './insure-component/trial-items'
import ProtectItems from './insure-component/protect-items'
import StartDate from './insure-component/start-date'
import Trial from '../trial'
import { API } from '../../api'

const CheckboxItem = Checkbox.CheckboxItem

class App extends React.Component {
  constructor (props) {
    super(props)

    this.handleSubmit = this.handleSubmit.bind(this)
    this.changePrice = this.changePrice.bind(this)
    this.trialPrice = this.trialPrice.bind(this)

    this.cuid = T.urlQuery('cuid') || 'Adsfyh4540887f'
    this.sessionKey = 'insure_' + this.cuid
    let factors = T.sessionStorage.get('calculateVals')
    if (factors) {
      factors = JSON.parse(factors)
    }

    this.state = {
      tongyi1: false,
      tongyi2: false,
      price: T.sessionStorage.get('price') || '0',
      trialFactors: Trial.getInitTrialFactors(),
      priceDetail: {}
    }
    actions.insureModel.clearErrorMap()
  }
  componentDidMount () {
    actions.insureModel.requestBlockInfo()

    actions.insureModel.requestInsureInfo(({ initValueObj, initInfo }) => {
      this.afterRequestAction(initValueObj, initInfo)
    })

    window.scrollTo(0, 0)

    T.setColor()
  }

  afterRequestAction (initValueObj, initInfo) {
    this.setState({
      tongyi1: initInfo.tongyi1,
      tongyi2: initInfo.tongyi2
    })

    this.trialPriceAction()
  }

  trialPrice (key, value) {
    if (value instanceof Date) {
      value = T.formatDate('yyyy-MM-dd', value) + ' 00:00:00'
    }
    let factorParams = this.state.trialFactors
    if (key) {
      if (typeof key === 'string') {
        if (factorParams[key]) {
          factorParams[key] = value
          this.trialPriceAction(factorParams)
        }
      }

      if (typeof key === 'object') {
        let flag = false
        for (let tkey in key) {
          if (factorParams[tkey] && key[tkey]) {
            flag = true
            if (T.isArray(key[tkey])) { // 如果就是要数组  这里要改一下
              factorParams[tkey] = key[tkey][0]
            } else {
              factorParams[tkey] = key[tkey]
            }
          }
        }

        if (flag) {
          this.trialPriceAction(factorParams)
        }
      }
    } else {
      this.trialPriceAction()
    }
  }

  trialPriceAction (factorParams) {
    factorParams = factorParams || this.state.trialFactors || {}
    let channelGoodsId = T.urlQuery('channelGoodsId')
    let channelPlanId = T.urlQuery('planId')
    if (!Object.keys(factorParams).length) {
      return
    }
    Trial.trialPrice({ channelGoodsId, channelPlanId, factorParams }, (price, detail) => {
      this.setState({ trialFactors: factorParams, priceDetail: detail })
      this.changePrice(price)
    })
  }

  changePrice (price = 0) {
    price = (+price).toFixed(2)
    this.setState({ price })
  }

  getParam (values) {
    let param = {
      1: [],
      2: []
    }
    let temp
    let type
    let key
    let value
    let indexId
    let protectObj = {}
    let sid
    let benefitDataMap = {}
    for (let filedKey in values) {
      value = values[filedKey]
      if (value instanceof Date) {
        value = T.formatDate('yyyy-MM-dd', value) + ' 00:00:00'
        values[filedKey] = value
      }
      if (T.isArray(value) && value.length === 1) {
        value = value[0]
      }

      temp = filedKey.split('_')
      if (temp.length === 4) {
        key = temp[0]
        type = temp[1]
        indexId = parseInt(temp[2]) - 1

        if (type === '3') {
          sid = temp[3]
          benefitDataMap[sid] = benefitDataMap[sid] || []
          benefitDataMap[sid][indexId] = benefitDataMap[sid][indexId] || {}
          benefitDataMap[sid][indexId][key] = value
        } else {
          param[type] = param[type] || []
          param[type][indexId] = param[type][indexId] || {}
          param[type][indexId][key] = value
        }
      } else {
        protectObj[filedKey] = value
      }
    }

    if (param[2]) {
      param[2].forEach((item, index) => {
        if (benefitDataMap[index + 1]) {
          // item.benefitType = 2
          item.benefits = benefitDataMap[index + 1].filter((item) => item !== undefined)
        } else {
          // item.benefitType = 1
        }
      })
      param[2] = param[2].filter((item) => item !== undefined)
    }
    if (param[2]) {
      let judgeFlag = true
      param[2].forEach((item, index) => {
        if (item.benefits) {
          let bilis = T.pluck(item.benefits, 'benefitRatio')
          let totalBili = parseInt(T.sum(bilis))
          if (totalBili !== 100) {
            T.showError('受保人' + (index + 1) + '的受益人受益比例之和须为100%', 4)
            judgeFlag = false
            return false
          }
        }
      })
      if (!judgeFlag) {
        return
      }
    }

    let holderParam = param[1][0] || {}
    let insurantParam = param[2][0] || {}
    if (insurantParam.relationWithHolders === '1') { // 本人
      let tempObj = this.applicantBlockItem || {}
      let tempBlocks = (tempObj && tempObj.selector && tempObj.selector.props && tempObj.selector.props.blocksMap) || {}
      tempBlocks = tempBlocks[1]
      if (tempBlocks) {
        tempBlocks.forEach((tt, index) => {
          let keycode = tt.customizeCode
          if (insurantParam[keycode] === undefined) {
            insurantParam[keycode] = holderParam[keycode]
          }
        })
      } else {
        console.log('没有获取到投保人字段')
        insurantParam = { ...insurantParam, ...holderParam }
      }
    }

    if (values.effectiveTime && values.effectiveTime.length <= 10) {
      values.effectiveTime = values.effectiveTime + ' 00:00:00'
    }

    return {
      'amount': this.state.price,
      'channelGoodsId': T.urlQuery('channelGoodsId'),
      'planId': T.urlQuery('planId'),
      'planName': T.urlQuery('planName'), // 计划名称
      'channelGoodsName': T.urlQuery('productName'),
      'effectiveTime': values.effectiveTime,
      'policyHolder': holderParam,
      'insuredList': [insurantParam],
      'extraInfo': this.state.trialFactors,
      'detail': this.state.priceDetail,
      'userId': ''
    }
  }

  showTopErrorMsg (errMsgObj = {}) {
    // let errMsgObj = this.props.form.getFieldsError()
    const Lang = window.LangMessage || {}
    for (let key in errMsgObj) {
      if (errMsgObj[key]) {
        let errType = key.split('_')[1]
        let block = errType === '1' ? (Lang.holder || '投保人') : (errType === '2' ? (Lang.insurant_text || '受保人') : (Lang.beneficiary || '受益人'))
        let msg = errMsgObj[key].errors[0].message
        actions.insureModel.setErrorMap(errMsgObj)
        T.showError(block + ' ' + (Lang.info_error || ' info error') + ': ' + msg, 4)
        break
      }
    }
  }

  handleSubmit (e) {
    const { tongyi } = this.state
    const Lang = window.LangMessage || {}
    e.preventDefault()
    this.props.form.validateFields({ first: true, force: true }, (err, values) => {
      console.log('Received values of form: ', values)
      if (err) {
        this.showTopErrorMsg(err)
        console.log('err ', err)
        return
      }
      let param = this.getParam(values)
      if (!param) {
        return
      }

      T.sessionStorage.set(this.sessionKey, JSON.stringify(param))

      console.log('【param】', param)

      if (!tongyi) {
        return T.showError(Lang.check_agree_insure_protcol || '请勾选我已阅读《投保须知》和《保险条款》')
      }

      T.fetch2({
        url: API.submitOrder.path,
        loading: true,
        data: param
      }).then((result) => {
        if (result.success) {
          let data = result.value || {}
          T.sessionStorage.set('price', this.state.price)
          T.sessionStorage.set('calculateVals', this.state.trialFactors)
          actions.routing.push({ pathname: 'pay-yj-en', search: '?orderNo=' + data.orderNo + '&productName=' + T.urlQuery('productName') })
        }
      })
    })
  }

  render () {
    let { tongyi, price = '0' } = this.state
    price = T.cutPrice(price)
    const { step = 1 } = this.props
    const Lang = window.LangMessage || {}
    console.log(this.trialPrice)
    return (
      <div className='insure-wrap' style={{ minHeight: T.getScreenHeight() }}>

        <div className='body'>

          <div>
            <HolderBox
              step={step}
              form={this.props.form}
              trialPrice={this.trialPrice}
              ref={(item) => {
                this.applicantBlockItem = item || {}
              }}
            />
            <InsuranceBox
              step={step}
              trialPrice={this.trialPrice}
              form={this.props.form}
            />

            <StartDate form={this.props.form} trialPrice={this.trialPrice} />
          </div>

          {/* <TrialItems
            data={trialItems}
            step={step}
            changePrice={this.changePrice}
            form={this.props.form}
          />

          <ProtectItems data={protectDetail} step={step} /> */}

          {step === 1 &&
            <div className='agree-div'>
              <div className='clearfix'>
                <div className='fl check-div'>
                  <CheckboxItem
                    checked={tongyi}
                    onChange={(e) => this.setState(oldState => Object.assign(oldState, { tongyi: !oldState.tongyi }))}
                  />
                </div>
                <div className='fl word-div word-div2'>
                  {Lang.has_read || '我已阅读'}
                  <span className='diy_color'>《{Lang.insure_must_know || '投保须知'}》</span>{Lang.web_and || '和'}
                  <span className='diy_color'>《{Lang.policy_items || '保险条款'}》</span>
                </div>
              </div>
            </div>
          }
        </div>

        <div className='blank-div-100' />
        <div className='fixed-foot clearfix insure-bottom'>
          <div className='fl pl30'>{Lang.policy_fee || '保费'}：<span className='color-price f34 ml20'>${T.formatPrice(price)}</span></div>
          <div className='fr tac f32 diy_background' onClick={this.handleSubmit}>{Lang.pay_now || '立即支付'}</div>
        </div>
      </div>
    )
  }
}

export default createForm()(App)
